<template>
  <div class="aiot-container" ref="container" :class="theme">
    <div class="tabs">
      <h3
        v-for="(item,index) in tabs"
        :key="index"
        :class="[currentIndex === index ? 'active' : 'lose']"
        @click="currentIndex=index"
      >{{ item.name }}</h3>
    </div>
    <div v-if="tabs[currentIndex].component == 'watermeter'" class="box">
      <dv-box title="智能水表">
        <div class="water">
          <div class="water1">
            <h5 class="h5-color">智能水表</h5>
            <div style="height:calc(100% - 36px)">
              <Echart
                id="water1"
                :options="waterOptions1"
                width="100%"
                height="100%"
              >
              </Echart>
            </div>
            
            <div class="item">
              <div>
                <span>水费:</span>
                <span>{{waterData.costfee.toFixed(2)}}元</span>
              </div>
              <div>
                <span>环比:</span>
                <i
                  :style="{color: waterData.day_ratio >=0 ? '#F6C424' : '#24F7B2'}"
                  class="iconfont"
                  :class="[waterData.day_ratio >= 0
                    ? 'icon-tubiaoshangshengqushi'
                    : 'icon-tubiaoxiajiangqushi'
                  ]"
                ></i>
                <span
                  :style="{color: waterData.day_ratio >=0 ? '#F6C424' : '#24F7B2'}"
                >{{Math.abs(waterData.day_ratio)}} %</span>
              </div>
            </div>
          </div>
          <div class="water2">
            <h5 class="h5-color">水表在线率</h5>
            <div style="height:calc(100% - 36px)">
              <Echart
                id="water2"
                :options="waterOptions2"
                height="100%"
                width="100%"
              >
              </Echart>
            </div>
            
          </div>
          <div class="water3">
            <h5 class="h5-color">分析使用</h5>
            <div style="height:calc(100% - 36px)">
              <Echart
                id="water3"
                :options="waterOptions3"
                height="100%"
                width="100%"
              >
              </Echart>
            </div>
          </div>
        </div>
      </dv-box>
      <dv-box title="智能电表">
        <div class="electric">
          <div class="electric1">
            <h5 class="h5-color">智能电表</h5>
            <div style="height:calc(100% - 36px)">
              <Echart
                id="electric1"
                :options="electricOptions1"
                height="100%"
                width="100%"
              >
              </Echart>
            </div>
            <div class="item">
              <div>
                <span>电费:</span>
                <span>{{ electricData.costfee.toFixed(2) }}元</span>
              </div>
              <div>
                <span>环比:</span>
                <i
                  :style="{color: electricData.day_ratio >=0 ? '#F6C424' : '#24F7B2'}"
                  class="iconfont icon-tubiaoshangshengqushi"
                  :class="[electricData.day_ratio >= 0
                    ? 'icon-tubiaoshangshengqushi'
                    : 'icon-tubiaoxiajiangqushi'
                  ]"
                ></i>
                <span
                  :style="{color: electricData.day_ratio >=0 ? '#F6C424' : '#24F7B2'}"
                >{{Math.abs(electricData.day_ratio)}} %</span>
              </div>
            </div>
          </div>
          <div class="electric2">
            <h5 class="h5-color">电表在线率</h5>
            <div style="height:calc(100% - 36px)">
              <Echart
                id="electric2"
                :options="electricOptions2"
                height="100%"
                width="100%"
              >
              </Echart>
            </div>
          </div>
          <div class="electric3">
            <h5 class="h5-color">分析使用</h5>
            <div style="height:calc(100% - 36px)">
              <Echart
                id="electric3"
                :options="electricOptions3"
                height="100%"
                width="100%"
              >
              </Echart>
            </div>
          </div>
        </div>
      </dv-box>
      <dv-box title="能耗趋势">
        <div class="detection">
          <Echart
            id="detection"
            :options="detectionOptions"
            height="100%"
            width="48vw"
          >
          </Echart>
        </div>
      </dv-box>
      <dv-box title="历史报告">
        <div class="report">
          <dv-scroll-board :config="tableConfig" />
        </div>
      </dv-box>
    </div>
    <tower :id="id" v-if="tabs[currentIndex].component == 'tower'"></tower>
    <elevarot :id="id" v-if="tabs[currentIndex].component == 'elevarot'"></elevarot>
  </div>
</template>

<script>
import dvBox from "@/components/datav/dv-box.vue";
import Echart from "@/components/echart";
import tower from "./tower"
import elevarot from './elevarot'
import moment from "moment";
import {mapGetters} from "vuex";
export default {
  props:{
    id:{
      type:Number|String,
      default:''
    },
    project:{
      type:Object|String,
      default:''
    }
  },
  components: {
    dvBox,
    Echart,
    tower,
    elevarot
  },
  data(){
    return {
      currentIndex: 0,
      auths:[
        {name:'塔机监测',code:'1-3-2',component:'tower'},
        {name:'施工电梯',code:'1-3-3',component:'elevarot'},
        {name:'智能水电表',code:'1-3-1',component:'watermeter'},
      ],
      detectionAxis: [],
      detectionSeries: [],
      waterData: {
        costvalue: 0,
        costfee: 0,
        costtotal: 0,
        day_ratio: 0
      },
      electricData: {
        costvalue: 0,
        costfee: 0,
        costtotal: 0,
        day_ratio: 0
      },
      waterArea: [],
      electricArea: [],
      waterOnline: 0,
      electricOnline: 0,
      tableData: [],
      contentHeight: 0,
      contentWidth: 0,
      rowNum: 0,
    }
  },
  mounted() {
    this.initData()
    const resizeObserver = new ResizeObserver((res) => {
      //this.contentHeight = res[0].contentRect.height / 2 - 130;
      this.contentWidth = res[0].contentRect.width;
      //this.rowNum = Math.round(this.contentHeight / 50)
    });
    resizeObserver.observe(this.$refs.container);
    this.$once('hook:beforeDestroy', () => {
      resizeObserver.disconnect();
    });
  },
  computed: {
    ...mapGetters(["theme"]),
    tableStyle(){
      return {
        height: this.contentHeight + 'px'
      }
    },
    tabs(){
      let arr = []
      this.auths.map(item => {
        if(this.project.moduleIds.indexOf(item.code) > -1){
          arr.push(item)
        }
      })
      return arr
    },
    projId(){
      return this.$route.query.id
    },
    tableConfig(){
      return {
        header: ['区域', '设备名称','设备编号', '开始消耗','结束消耗', '时间'],
        index: true,
        rowNum: 6,
        headerHeight:40,
        columnWidth:[
          50,
          this.contentWidth / 12,
          this.contentWidth / 12,
          this.contentWidth / 12,
          this.contentWidth / 12,
          this.contentWidth / 12,
          this.contentWidth / 12,
        ],
        headerBGC:'#F2F3F5',
        oddRowBGC:'rgba(0,0,0,0)',
        evenRowBGC:'rgba(0,0,0,0)',
        data: this.tableData
      }
    },
    waterOptions1(){
      return this.getOptions1({
        title: '今日用水量(t)',
        value: Math.round(this.waterData.costvalue).toString(),
        backgroundColor: [
          'rgba(62, 155, 255, 1)',
          'rgba(26, 92, 243, 1)'
        ]
      })
    },
    waterOptions2(){
      return this.getOptions2({
        title: '水表在线率',
        value: this.waterOnline,
        data: [
          {
            name: '在线',
            value: this.waterOnline,
            itemStyle: {
              color: 'rgba(3, 116, 254, 1)'
            }
          },
          {
            name: '离线',
            value: 100 - this.waterOnline,
            itemStyle: {
              color: 'rgba(155, 156, 179, 1)'
            }
          }
        ],
        borderColor: 'rgba(0, 130, 255, 1)'
      })
    },
    waterOptions3(){
      return this.getOptions3({
        title: '总用水量(t)',
        value: Math.round(this.waterData.costtotal).toString(),
        color: [
          'rgba(61, 242, 183, 1)',
          'rgba(0, 130, 255, 1)',
          'rgba(102, 225, 223, 1)'
        ],
        backgroundColor: 'rgba(3, 116, 254, 0.1)',
        data: this.waterArea
      })
    },
    electricOptions1(){
      return this.getOptions1({
        title: '今日用电量(kwh)',
        value: Math.round(this.electricData.costvalue).toString(),
        backgroundColor: [
          'rgba(254, 158, 32, 1)',
          'rgba(222, 134, 18, 1)'
        ]
      })
    },
    electricOptions2(){
      return this.getOptions2({
        title: '电表在线率',
        value: this.electricOnline,
        data: [
          {
            name: '在线',
            value: this.electricOnline,
            itemStyle: {
              color: 'rgba(3, 116, 254, 1)'
            }
          },
          {
            name: '离线',
            value: 100 - this.electricOnline,
            itemStyle: {
              color: 'rgba(155, 156, 179, 1)'
            }
          }
        ],
        borderColor: 'rgba(0, 130, 255, 1)'
      })
    },
    electricOptions3(){
      return this.getOptions3({
        title: '总用电量(kwh)',
        value: Math.round(this.electricData.costtotal).toString(),
        color: [
          'rgba(250, 212, 60, 1)',
          'rgba(234, 96, 52, 1)',
          'rgba(255, 218, 152, 1)'
        ],
        backgroundColor: 'rgba(254, 152, 17, 0.1)',
        data: this.electricArea
      })
    },
    detectionOptions(){
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
        },
        grid: {
          top: 30,
          bottom: 30,
          right: 30,
          left: 40
        },
        xAxis: {
          type: 'category',
          axisTick: {
            show: false
          },
          axisLabel: {
            margin: 12,
            color:'#000',
          },
          data: this.detectionAxis,
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel:{
            color:'#000'
          }
        },
        series: this.detectionSeries.map(item=>{
          return {
            type: item.type,
            data: item.data,
            name: item.name,
            smooth: false,
            barMaxWidth: 12,
            barGap: 0.5,
            label: {
              show: false
            },
            itemStyle: {
              color: item.color
            }
          }
        })
      }
    }
  },
  methods: {
    initData(){
      this.$api.getWaterTotal({
        projectid: this.projId,
        type: 'day'
      }).then(res=>{
        this.waterData = res.data
      })
      this.$api.getElectricTotal({
        projectid: this.projId,
        type: 'day'
      }).then(res=>{
        this.electricData = res.data
      })
      this.$api.getWaterArea({
        projectid: this.projId,
        today: moment().format('YYYY-MM-DD')
      }).then(res=>{
        this.waterArea = res.data.map(item=>{
          return {
            name: item.area,
            value: item.value
          }
        })
      })
      this.$api.getElectricArea({
        projectid: this.projId,
        today: moment().format('YYYY-MM-DD')
      }).then(res=>{
        this.electricArea = res.data.map(item=>{
          return {
            name: item.area,
            value: item.value
          }
        })
      })
      Promise.all([
        this.$api.getWaterOnline({
          projectid: this.projId,
        }),
        this.$api.getElectricOnline({
          projectid: this.projId,
        })
      ]).then(res=>{
        const water = res[0].data
        const electric = res[1].data
        this.waterOnline = water.tot
          ? ((water.online) / (water.tot) * 100).toFixed(0)
          : 0
        this.electricOnline = electric.tot
          ? ((electric.online) / (electric.tot) * 100).toFixed(0)
          : 0
      })
      Promise.all([
        this.$api.getWaterTrend({
          projectid: this.projId,
          start: moment().subtract(6,'day').format('YYYY-MM-DD'),
          end: moment().format('YYYY-MM-DD')
        }),
        this.$api.getElectricTrend({
          projectid: this.projId,
          start: moment().subtract(6,'day').format('YYYY-MM-DD'),
          end: moment().format('YYYY-MM-DD')
        })
      ]).then(res=>{
        const water = {}
        const electric = {}
        Object.values(res[0].data).flat().forEach(item=>{
          if(!water[item.partitiondate]){
            water[item.partitiondate] = item.costvalue
          } else {
            water[item.partitiondate] += item.costvalue
          }
          water[item.partitiondate] = parseInt(water[item.partitiondate].toFixed(2))
        })
        Object.values(res[1].data).flat().forEach(item=>{
          if(!electric[item.partitiondate]){
            electric[item.partitiondate] = item.costvalue
          } else {
            electric[item.partitiondate] += item.costvalue
          }
          electric[item.partitiondate] = parseInt(electric[item.partitiondate].toFixed(2))
        })
        this.detectionAxis = [
          ...new Set([
            ...Object.keys(water),
            ...Object.keys(electric)
          ])
        ]
        this.$set(this.detectionSeries,0,{
          type: 'bar',
          name: '水表',
          color: 'rgba(155, 156, 179, 1)',
          data: [...Object.values(water)]
        })
        this.$set(this.detectionSeries,1,{
          type: 'bar',
          name: '电表',
          color: 'rgba(11, 126, 255, 1)',
          data: [...Object.values(electric)]
        })
      })
      Promise.all([
        this.$api.getWaterConsume({
          projectid: this.projId,
          start: moment().subtract(6,'day').format('YYYY-MM-DD'),
          end: moment().format('YYYY-MM-DD')
        }),
        this.$api.getElectricConsume({
          projectid: this.projId,
          start: moment().subtract(6,'day').format('YYYY-MM-DD'),
          end: moment().format('YYYY-MM-DD')
        })
      ]).then(res=>{
        const waterList = res[0].data.content
        const electricList = res[1].data.content
        waterList.forEach(item=>{
          this.tableData.push([
            item.area,
            item.name,
            item.devicesn,
            item.startcost.toFixed(2),
            item.endcost.toFixed(2),
            item.partitiondate
          ])
        })
        electricList.forEach(item=>{
          this.tableData.push([
            item.area,
            item.name,
            item.devicesn,
            item.startcost.toFixed(2),
            item.endcost.toFixed(2),
            item.partitiondate
          ])
        })
      })
    },
    getOptions1(params){
      return {
        title: {
          text: params.title,
          subtext: params.value,
          left: 'center',
          top: '24%',
          itemGap: 20,
          textStyle: {
            color:'#fff',
            fontSize: 15,
            lineHeight: 23
          },
          subtextStyle: {
            color:'#fff',
            fontSize: 40,
            lineHeight: 26,
            fontWeight: 'bold',
          }
        },
        series: [
          {
            type: "pie",
            center: ['50%', '40%'],
            radius: "60%",
            animation: false,
            hoverAnimation: false,
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 5,
              color: {
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: params.backgroundColor[0]
                  },
                  {
                    offset: 1,
                    color: params.backgroundColor[1]
                  }
                ]},
            },
            data: [100],
          },
        ]
      }
    },
    getOptions2(params){
      return {
        title: {
          text: params.title,
          subtext: params.value + '%',
          left: 'center',
          top: '42%',
          itemGap: -55,
          textStyle: {
            color:'#000',
            fontSize: 10,
            lineHeight: 23
          },
          subtextStyle: {
            color:'#000',
            fontSize: 22,
            lineHeight: 26,
            fontWeight: 'bold',
            // fontFamily: 'YouSheBiaoTiHei'
          }
        },
        legend: {
          show: true,
          bottom: 0,
          icon: 'rect',
          itemWidth:8,
          itemHeight:8,
          itemGap: 30,
          textStyle:{
              color:'#000'
          }
        },
        series: [
          {
            type: 'pie',
            center: ['50%', '40%'],
            radius: ['45%', '60%'],
            animation: false,
            hoverAnimation: false,
            label: {
              show: false
            },
            data: params.data
          },
          {
            type: 'pie',
            center: ['50%', '40%'],
            radius: ['32%', '40%'],
            animation: false,
            hoverAnimation: false,
            label: {
              show: false
            },
            itemStyle: {
              color: 'rgba(202, 206, 230, 1)'
            },
            data: [100]
          },
        ]
      }
    },
    getOptions3(params){
      return {
        title: {
          text: params.value,
          subtext: params.title,
          left: 'center',
          top: '32%',
          itemGap: 5,
          textStyle: {
            color: '#000',
            fontSize: 42,
            lineHeight: 24
          },
          subtextStyle: {
            color: '#000',
            fontSize: 13,
            lineHeight: 12,
            fontWeight: 'bold',
            // fontFamily: 'YouSheBiaoTiHei'
          }
        },
        legend: {
          show: true,
          bottom: 0,
          icon: 'circle',
          itemWidth:12,
          textStyle:{
              color:'#000'
          },
          formatter: val => {
            return val + ' ' + params.data
              .find(item=>item.name === val)?.value.toFixed(2) + 't' ?? ''
          }
        },
        series: [
          {
            type: 'pie',
            center: ['50%', '40%'],
            radius: ['52%', '60%'],
            animation: false,
            hoverAnimation: false,
            itemStyle: {
              borderWidth: 5,
              borderColor: 'rgba(245,250,270,1)'
            },
            label: {
              show: false
            },
            color: params.color,
            data: params.data
          },
          {
            type: "pie",
            center: ['50%', '40%'],
            radius: "45%",
            animation: false,
            hoverAnimation: false,
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            itemStyle: {
              color: params.backgroundColor
            },
            data: [100],
          },
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.aiot-container {
  height: 100%;
  width: calc(100vw - 40px);
  overflow: hidden;

  .tabs {
    display: flex;
    justify-content: center;

    .active {
      color: rgba(255, 255, 255, 1);
      background: linear-gradient(90deg, #1D42AB 0%, #1E91FE 100%);
    }

    .lose {
      color: rgba(255, 255, 255, 1);
      background-color: rgba(155, 156, 179, 1);
    }

    > h3 {
      font-size: 15px;
      font-weight: 400;
      line-height: 30px;
      height: 30px;
      margin: 0 10px;
      width: 160px;
      text-align: center;
      cursor: pointer;
    }
  }
  .box {
    margin-top: 24px;
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    grid-gap: 24px;
    height: calc(100% - 60px);
    min-height: 676px;
  }

  .water,.electric {
    display: flex;
    height: 100%;
    > div {
      flex: 1;
      overflow: hidden;

      h5 {
        font-size: 18px;
        font-family: SourceHanSansCN-Medium, SourceHanSansCN;
        font-weight: 500;
        color: #D9E7FF;
        line-height: 16px;
        padding: 8px 12px;
        margin: 0 10px;
        border-radius: 15px 0 0 0;
        border: 1px solid rgba(0, 130, 255, 1);
      }
    }
    .h5-color{
        color: #0A0B0F;
    }
    .water1,.electric1 {
      position: relative;
      height: 100%;
      .item {
        position: absolute;
        left: 70px;
        bottom: 0;
        display: flex;
        flex-direction: column;
        margin-top: 20px;

        div {
          display: flex;
          align-items: center;

          span {
            &:first-child{
              font-size: 14px;
              font-family: MicrosoftYaHei;
              color: #000;
              line-height: 26px;
              margin-right: 10px;
            }
          }
          &:first-child {
            span {
              &:last-child {
                font-size: 16px;
                font-family: YouSheBiaoTiHei;
                color: #159AFF;
                line-height: 26px;
                text-shadow: 0px 0px 10px #159AFF;
              }
            }
          }

          &:last-child {
            i {
              margin-right: 5px;
            }
            span {
              &:last-child {
                font-size: 14px;
                font-family: MicrosoftYaHei;
                line-height: 26px;
              }
            }
          }
        }
      }
    }
  }
}
.detection,.report{
  height: 100%;
}
@include dvScroll
</style>